package com.mainbo.modular.system.controller.user;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.mainbo.core.common.constant.ApolloConstants;
import com.mainbo.core.common.constant.ConfigUtils;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.core.util.StringUtil;
import com.mainbo.modular.excel.ExcelBatchService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.Teacher;
import com.mainbo.modular.system.model.meta.*;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.ExportInfoVo;
import com.mainbo.modular.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import com.mainbo.core.log.LogObjectHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2020-02-22 16:04:40
 */
@Controller
@RequestMapping("/ptTeacher")
public class PtTeacherController extends BaseController {
    private final static Logger logger= LoggerFactory.getLogger(PtTeacherController.class);
    private String PREFIX = "/system/ptTeacher/";

    @Resource
    private TeacherService teacherService;
    @Resource
    private IPtRoleService roleService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private IPtAccountService accountService;
    @Resource(name = "batchExportUserServiceImpl")
    private ExcelBatchService batchExportUserService;
    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index(UserSearchModel um,Model model) {
        PtOrg org = ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
//        if (org != null && StringUtils.isNotEmpty(org.getId()) && StringUtils.isBlank(um.getOrgId())
//                && um.getAreaId() == null) {
//            um.setOrgId(org.getId());
//        }
//        um.setUserType(PtAccount.TEACHER_USER);
//        List<Teacher> list = teacherService.findTeacherList(teacher, um);
//        model.addAttribute("userList", list);
        List<SysRole> sysRoles=SysRole.listForScope(2);
        model.addAttribute("sysRoles",sysRoles);

        // 获取职务集合
        List<PtRole> roles = roleService.getRoleByScope(null, PtRoleType.APPLICATION_SCHOOL);
        model.addAttribute("roles", roles);
        if ((org == null)) {
            model.addAttribute("orgId","0");
            return PREFIX + "ptTeacher_org.html";
        }else {
            if (org.getSchoolings() != null && Integer.valueOf(PtOrg.TP_SCHOOL).equals(org.getType())) {
                model.addAttribute("phases", MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings()));
            }
            // 年级、学科集合
            if (um.getPhaseId() != null && um.getPhaseId() != 0) {
                List<Meta> grades = MetaUtils.getOrgTypeProvider().listAllGrade(org.getSchoolings(), um.getPhaseId());
                Integer[] areaIds = com.mainbo.utils.StringUtils
                        .toIntegerArray(org.getAreaIds().substring(1, org.getAreaIds().lastIndexOf(",")), ",");
                List<Meta> subjects = MetaUtils.getPhaseSubjectProvider().listAllSubject(org.getId(), um.getPhaseId(),
                        areaIds);
                model.addAttribute("grades", grades);
                model.addAttribute("subjects", subjects);
            }
        }
        model.addAttribute("org",org);
        return PREFIX + "ptTeacher_list.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptTeacher_add")
    public String ptTeacherAdd(String orgId,Model model) {
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        PtOrg org=orgService.selectById(orgId);
        List<SysRole> sysRoles=SysRole.listForScope(2);
        model.addAttribute("org",org);
        model.addAttribute("sysRoles",sysRoles);
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBPapersType", GBPapersType.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPolitical", GBPolitical.values());
        return PREFIX + "ptTeacher_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptTeacher_update/{ptTeacherId}")
    public String ptTeacherUpdate(@PathVariable String ptTeacherId, Model model) {
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        Teacher ptTeacher = teacherService.selectById(ptTeacherId);
        PtAccount account=accountService.selectById(ptTeacherId);
        ptTeacher.setUserType(account.getUserType());
        List<SysRole> sysRoles=SysRole.listForScope(2);
        model.addAttribute("sysRoles",sysRoles);
        model.addAttribute("GBSex", GBSex.values());
        model.addAttribute("GBPapersType", GBPapersType.values());
        model.addAttribute("GBNation", GBNation.values());
        model.addAttribute("GBPolitical", GBPolitical.values());
        model.addAttribute("item",ptTeacher);
        LogObjectHolder.me().set(ptTeacher);
        return PREFIX + "ptTeacher_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(UserSearchModel um,Teacher teacher) {
        if (StringUtils.isBlank(um.getOrgId())){
            return new ArrayList<Student>();
        }

        return teacherService.findTeacherList(teacher,um);
    }
    /**
     * 跳转到查看
     */
    @RequestMapping("/ptTeacher_showInfo/{id}")
    public String ptTeacherShowInfo(@PathVariable String id, Model model) {
        Teacher teacher=teacherService.selectById(id);
        PtAccount account=accountService.selectById(id);
        teacher.setAccountName(account.getAccount());
        model.addAttribute("item",teacher);
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        model.addAttribute("sysRole", SysRole.forCname(account.getUserType()));
        model.addAttribute("sex", GBSex.forCname(teacher.getSex()));
        model.addAttribute("nation", GBNation.forCname(teacher.getNationCode()));
        if (StringUtils.isBlank(teacher.getPoliticalStatus())){
            model.addAttribute("GBPolitical","");
        }else {
            model.addAttribute("GBPolitical", GBPolitical.forCname(Integer.valueOf(teacher.getPoliticalStatus())));
        }
        if (teacher.getPapersType()==null){
            model.addAttribute("GBPapersType","");
        }else {
            model.addAttribute("GBPapersType", GBPapersType.forCname(teacher.getPapersType()));
        }
        if (teacher.getNationCode()==null){
            model.addAttribute("GBNation","");
        }else {
            model.addAttribute("GBNation", GBNation.forCname(teacher.getNationCode()));
        }
        LogObjectHolder.me().set(teacher);
        return PREFIX + "ptTeacher_view.html";
    }
    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Result add(Integer userType, Teacher teacher) {
        Result result = new Result();
        try {
            result.setCode(Result.SUCCESS);
            teacher = teacherService.saveTeac(userType, teacher);
            result.setMsg(
                    "1".equals(teacher.getFlago()) || StringUtils.isBlank(teacher.getCellphone()) ? "保存成功" : "手机已被占用，可在个人中心绑定找回");
            accountService.sendUserMessege(MessageTypes.USER_ADD.name(), teacher.getId());
            logger.info(
                    "1".equals(teacher.getFlago()) || StringUtils.isBlank(teacher.getCellphone()) ? "保存成功" : "手机已被占用，可在个人中心绑定找回");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("保存失败", e);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 删除学生数据
     *
     * @param teacherId
     *          学生id
     * @param deleted
     *          是否删除
     * @return 返回
     */
    @RequestMapping(value = "/delete/{teacherId}")
    @ResponseBody
    public Result delete(@PathVariable String teacherId, Boolean deleted) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            accountService.deleteUser(teacherId, deleted);


            result.setMsg("删除成功");
            logger.info("操作成功");
        } catch (Exception e) {
            logger.info("删除败", e);
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Teacher ptTeacher) {
        teacherService.updateById(ptTeacher);
        return SUCCESS_TIP;
    }

    @RequestMapping("exportTeacher")
    public void exportEmp(UserSearchModel um, Teacher teacher, HttpServletResponse response, OutputStream os) {
        try {
            String fileName = "教职工用户信息表";
            if (um.getAreaId() != null) {
                String areaName = orgService.getAreaNameById(um.getAreaId());
                fileName = areaName + fileName;
            } else if (um.getOrgId() != null) {
                PtOrg org = orgService.selectById(teacher.getOrgId());
                if (org != null) {
                    String areaName = orgService.getAreaNameById(org.getAreaId());
                    fileName = areaName + org.getShortName() + fileName;
                }
            }
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
        } catch (UnsupportedEncodingException e) {
            logger.error("导出用户失败", e);
        }
        Map<String, Object> params = new HashMap<String, Object>();

        List<Map<Integer, String>> dataList = new ArrayList<>();

        List<ExportInfoVo> teacherList = teacherService.exportTeacherList(um);
        ExportInfoVo t = null;
        String password= ConfigUtils.readConfig(MetaKeys.PF_BACK_UC_PASSWORD_KEY, "000000");
        for (int i = 0; i < teacherList.size(); i++) {
            Map<Integer, String> dataMap = new HashMap<>();
            t = teacherList.get(i);
            String userRoleStr = accountService.exportUserRole(t.getId());
            dataMap.put(0, t.getAccountName());
            dataMap.put(1, t.getName());
            dataMap.put(2, SysRole.forCname(t.getUserType()));
            dataMap.put(3, userRoleStr);
            dataMap.put(4, GBSex.forCname(t.getSex()));
            dataMap.put(5, password);
            dataMap.put(6, t.getEnable() == true ? "否" : "是");
            dataMap.put(7,t.getSchoolCard());
            dataList.add(dataMap);
        }
        params.put("data", dataList);
        params.put("userType", PtAccount.TEACHER_USER);
        StringBuilder resultMsg = null;

        batchExportUserService.exportData(os, params, resultMsg, null);
    }

    /**
     * 批量删除
     *
     * @param accountIds
     *          要删除的id
     * @return Result
     */
    @RequestMapping("/batchdelete")
    @ResponseBody
    public Result batchdelete(String accountIds) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (!StringUtils.isEmpty(accountIds)) {
                for (String id : accountIds.split(",")) {
                    accountService.deleteUser(id, null);

                }
            }
            result.setMsg("删除成功");
            logger.info("删除成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("删除失败", e);
            result.setMsg("删除失败");
        }
        return result;
    }
    /**
     * 增加用户职务
     *
     * @param model
     *          数据模型
     * @param phaseId
     *          学段id
     * @param org
     *          机构
     * @return 返回
     */
    @RequestMapping("/sujectAndGradeInfoByPhase")
    @ResponseBody
    public Map<String, List<Meta>> sujectAndGradeInfoByPhase(Integer phaseId, PtOrg org) {
        String areaIds = org.getAreaIds();
        Integer[] areaId = StringUtil.toIntegerArray(areaIds.substring(1, areaIds.lastIndexOf(",")), ",");
        Map<String, List<Meta>> datas = new HashMap<String, List<Meta>>(2);
        org = orgService.selectById(org.getId());
        if (org != null) {
            datas.put("grades", MetaUtils.getOrgTypeProvider().listAllGrade(org.getSchoolings(), phaseId));
            datas.put("subjects", MetaUtils.getPhaseSubjectProvider().listAllSubject(org.getId(), phaseId, areaId));
        }
        return datas;
    }

}
